<?php
declare(strict_types=1);

namespace Dreamcat\ConfigClient\Nacos\Impl;


use Dreamcat\ConfigClient\Nacos\ConfigDecodeInterface;

/**
 * properties解析器
 * @author vijay
 */
class PropertiesDecoder implements ConfigDecodeInterface
{
    /**
     * @inheritDoc
     */
    public function decode(string $configString): array
    {
        $list = preg_split("#[\n\r]#", $configString);
        $configs = [];
        foreach ($list as $row) {
            $row = trim($row);
            if (!$row || $row[0] == "#") {
                continue;
            }
            $split = explode("=", $row, 2);
            $keys = explode(".", trim($split[0]));
            $val = trim($split[1] ?? "");
            $cur = &$configs;
            $cnt = count($keys) - 1;
            foreach ($keys as $idx => $key) {
                if ($idx == $cnt) {
                    $cur[$key] = $val;
                } else {
                    if (!isset($cur[$key])) {
                        $cur[$key] = [];
                    }
                    $cur = &$cur[$key];
                }
            }
        }
        return $configs;
    }
}

# end of file
